package crazy.crack;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

//所谓 anagram, 就是两个词所用的字母及其个数都是一样的，但是，字母的位置不一样。比如 abcc 和 cbca 就是 anagram
public class Anagram
{
	public static void main(String[] args)
	{
		System.out.println(anagram("abcc", "cacb"));
	}
	
	public static boolean anagram(String s, String t)
	{
		if (s.length() != t.length())
		{
			return false;
		}
		
		int[] letters = new int[256];
		int num_unique_chars = 0;
		int num_completed_t = 0;
		char[] s_array = s.toCharArray();
		for (char c : s_array)
		{
			//writeLog(c+" ");
			if (letters[c] == 0)
			{
				++num_unique_chars;
			}
			++letters[c];
		}
		

		
		for (int i = 0; i < t.length(); ++i)
		{
			int c = (int) t.charAt(i);
			if (letters[c] == 0)
			{
				return false;
			}
			--letters[c];
			if (letters[c] == 0)
			{
				++num_completed_t;
				if (num_completed_t == num_unique_chars)
				{
					return i == t.length() - 1;
				}
			}
		}
		return false;
	}
	
	public static void writeLog(String content)
	{
		BufferedWriter out = null;
		try
		{
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream("c:\\log.txt",true)));
			out.write(content+"\r\n");
			out.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
